package com.crm.dataReceive.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.crm.custinfo.domain.CustCommentRecord;
import com.crm.custinfo.domain.CustInfo;
import com.crm.custinfo.domain.HitPackage;
import com.crm.custinfo.service.ICustCommentRecordService;
import com.crm.custinfo.service.ICustInfoService;
import com.crm.custinfo.service.IHitPackageService;
import com.crm.dataReceive.domain.Customer;
import com.crm.dataReceive.domain.FzkjReq;
import com.crm.dataReceive.domain.jkyq;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.AesUtils;
import com.ruoyi.common.utils.Md5Encrypt;
import com.ruoyi.common.utils.ObjectUtil;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * fzkj八位撞库和进件接口，基本数和klhd一样
 */
@Slf4j
@RestController
@RequestMapping("/fz")
public class FzkjController {
    private final static String AES_KEY = "AkflV2OgjfFwuikB";
    private final static String IV = "83rs6r07eg5icqvi";
    public static String CODE = "code";
    public static String MSG = "msg";
    public static String DATA = "data";
    @Autowired
    private IHitPackageService hitPackageService;
    @Autowired
    private ICustInfoService custInfoService;
    @Autowired
    private ICustCommentRecordService custCommentRecordService;
    @Autowired
    private ISysConfigService baseSysConfigService;
    @PostMapping("check/tenant/{tenantId}")
    @ResponseBody
    @Anonymous
    public Map<String, Object> check(@RequestBody FzkjReq req) {
        String[] defaultData = new String[]{};
        try {

            String realRequestData = "";
            try {
                realRequestData = AesUtils.decrypt(req.getData(), AES_KEY, IV);
            } catch (Exception e) {
                log.error("fzkj解密异常[{}]", e.getMessage());
                return fzkjResult(500, "解密失败", "md5List", defaultData);
            }
            JSONObject jsonObject = JSONObject.parseObject(realRequestData);


            String encryptPhoneValue = jsonObject.getString("phone");
            if (StringUtils.isBlank(encryptPhoneValue) || encryptPhoneValue.length() != 8) {
                return fzkjResult(500, "手机号异常", "md5List", defaultData);
            }

            HitPackage hitPackage = new HitPackage();
            hitPackage.setMobilePrefix8Md5(Md5Encrypt.md5(encryptPhoneValue));
            List<HitPackage> custs= hitPackageService.selectHitPackageList(hitPackage);

            //List<HitPackage> custs = check4Perfix8Service.getHitPackages(req.getChannelSign(), city, mobileMd5);//getBusinessCode = channel_source

            if (CollectionUtils.isNotEmpty(custs)) {
                String[] data = new String[custs.size()];
                for (int i = 0; i < custs.size(); i++) {
                    data[i] = custs.get(i).getMobileMd5();
                }

                return fzkjResult(200, "success", "md5List", data);
            }
            return fzkjResult(200, "success", "md5List", defaultData);
        } catch (Exception e) {
            log.error("fzkj异常：" + e.getMessage());
            return fzkjResult(500, "api处理异常", "md5List", defaultData);
        }
    }

    @PostMapping("apply/tenant/{tenantId}")
    @ResponseBody
    @Anonymous
    public Map<String, Object> apply(@RequestBody FzkjReq req) {
        try {
            String realRequestData = "";
            try {
                realRequestData = AesUtils.decrypt(req.getData(), AES_KEY, IV);
            } catch (Exception e) {
                log.error("fzkj解密异常[{}]", e.getMessage());
                return fzkjResult(500, "解密失败fzkj");
            }
            if (StringUtils.isBlank(realRequestData)) {
                return fzkjResult(500, "解密失败fzkj");
            }
            //log.info("klhd解密[{}]", realRequestData);
            JSONObject jsonObject = JSONObject.parseObject(realRequestData);

            FzkjReq applyInfo = JSON.toJavaObject(jsonObject, FzkjReq.class);


            Customer customer = new Customer();
            customer.setMobile(applyInfo.getPhone());
            customer.setCustName(applyInfo.getUserName());

            String city = applyInfo.getCityName();
            city = city == null ? "" : city.replace("市", "");
            customer.setCity(city);

            // private Integer loanAmount;     //贷款额度1: 20万以上，2: 15-20万，3: 10-15万，4: 5-10万，5: 2000元-5万

            //StringUtils.defaultIfBlank(applyInfo.getLoanAmount(), "0")
            int loanAmount = 0;
            if (applyInfo.getLoanLimit() == 1) {
                loanAmount = 200000;
            } else if (applyInfo.getLoanLimit() == 2) {
                loanAmount = 150000;
            } else if (applyInfo.getLoanLimit() == 3) {
                loanAmount = 100000;
            } else if (applyInfo.getLoanLimit() == 4) {
                loanAmount = 50000;
            } else if (applyInfo.getLoanLimit() == 5) {
                loanAmount = 30000;
            }
            customer.setApplyLimit(new BigDecimal(loanAmount));

            // fz 1: 男，2: 女
            //我们性别(1:为男,2:为女,未知传0)

            customer.setSex(String.valueOf(applyInfo.getSex()));
            customer.setAge(Long.valueOf(applyInfo.getAge()));// 年龄
            customer.setChannelSource(req.getChannelSign());
            CustInfo custInfo = new CustInfo();
            ObjectUtil.copyProperties(customer, custInfo);

            //必填，1: 无本地公积金，2: 6个月以下，3: 6个月以上
            Integer accumulation = applyInfo.getAccumulation();
            if (accumulation == 1) {
                custInfo.setHasFund("0");
            } else{
                custInfo.setHasFund("1");
            }
            Integer socialSecurity = applyInfo.getSocialSecurity();
            if (socialSecurity == 1) {
                custInfo.setHasSocial("0");
            } else {
                custInfo.setHasSocial("1");
            }
            Integer house = applyInfo.getHouse();
            if (house == 1) {
                custInfo.setHasHouse("0");
            } else {
                custInfo.setHasHouse("1");
            }

            custInfo.setRepeatFlag("0");
            if (custInfo.getApplyTime() == null) {
                custInfo.setApplyTime(new Date());
            }
            String md5value = Md5Encrypt.md5(customer.getMobile());
            custInfo.setMd5val(md5value);
            custInfo.setDistributeId(-1L);
            if (custInfo.getApplyTime() == null) {
                custInfo.setApplyTime(new Date());
            }
            // 客户申请信息前置检查
            Map<String, Object> checkResult = custInfoService.checkCustInfo(custInfo, log);
            if (MapUtils.getIntValue(checkResult, "errorNo", -1) != 0) {
                return fzkjResult(500, MapUtils.getString(checkResult, "errorInfo", ""));
            }
            // 随机分配
            Long[] orgIds = custInfoService.getOrgIdsByCity(custInfo.getCity());
            boolean isSucceed = custInfoService.dealCustRandomly(custInfo, orgIds, true, false, log);
            if (isSucceed) {
                if (StringUtils.isNotBlank(custInfo.getRemark())) {
                    // 自动生成一条备注
                    CustCommentRecord record = new CustCommentRecord();
                    record.setCustId(custInfo.getId());
                    record.setEmpId(null);
                    record.setEmpName("系统自动备注");
                    record.setRemark(custInfo.getRemark());
                    record.setType(1L);
                    record.setType2(1L);
                    record.setCreateTime(new Date());
                    custCommentRecordService.insertCustCommentRecord(record);
                }
            } else {
                return fzkjResult(500, "线索接收API请求申请异常");
            }
            return fzkjResult(200, "成功");
        } catch (Exception e) {
            log.error("fzkj-apply异常：" + e.getMessage());
            return fzkjResult(500, "api处理异常fzkj");
        }

    }

    private Map<String, Object> fzkjResult(int code, String msg) {
        Map<String, Object> resMap = new HashMap<>(4);
        resMap.put(CODE, code);
        resMap.put(MSG, msg);
        return resMap;
    }

    private Map<String, Object> fzkjResult(int code, String msg, String dataName, String[] d) {
        Map<String, Object> resMap = new HashMap<>(4);
        resMap.put(CODE, code);
        resMap.put(MSG, msg);

        Map<String, Object> resMapData = new HashMap<>(4);
        resMapData.put(dataName, d);
        resMap.put(DATA, resMapData);
        return resMap;
    }

    //main 方法
    public static void main(String[] args) {
        Map<String, Object> resMap = new HashMap<>(4);
        //resMap.put("","")
//        String a = AesUtils.decrypt("cEHz6WrSLktmQUck3SaYU0iYWBH5NINSFM4FLhxfCq4=", AES_KEY, IV);

//        System.out.println(a);
        String input="{\"phone\":\"14400000000\",\"userName\":\"张三\",\"sex\":1,\"age\":30,\"cityName\":\"佛山\",\"overdueSituation\":2,\"loanLimit\":4,\"occupation\":1,\"accumulation\":3,\"socialSecurity\":3,\"car\":2,\"insurance\":3,\"sesameSeed\":4,\"house\":2,\"huaBei\":2,\"whiteStripe\":2,\"clockSalary\":3,\"creditCard\":2,\"education\":1}";
        System.out.println(AesUtils.encrypt(input, AES_KEY, IV));
    }


}
